package com.kiln.juxingqs.dialog

import android.content.Intent
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.*
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import client.global.commlib.network.data.JsonResult
import client.global.commlib.network.data.Ret
import client.global.commlib.toast.toast
import com.blankj.utilcode.util.LogUtils
import com.kiln.juxingqs.R
import com.kiln.juxingqs.adapter.Bank3Adapter
import com.kiln.juxingqs.api.bean.UserCards
import com.kiln.juxingqs.databinding.DialogPayDetailBinding
import com.kiln.juxingqs.ui.CreateBank3Activity
import com.kiln.juxingqs.ui.viewmodel.MiddleVm
import com.tzstore.oo.dialog.BottomBindingDialog

/**
 * Date: 2022/10/31 16:56
 * Description:
 */
class PayDetailDialog(private val context: FragmentActivity) : BottomBindingDialog<DialogPayDetailBinding>(context) {

    private var rePayWay: RelativeLayout? = null
    private var rePayDetail: RelativeLayout? = null
    private var reBalance: RelativeLayout? = null
    private var LinPayWay: LinearLayout? = null
    private var linPass: LinearLayout? = null
    private var rv: RecyclerView? = null

    private var btnPay: Button? = null
    private var gridPasswordView: EditText? = null
    private var llCloseOne: LinearLayout? = null
    private var imageCloseTwo: ImageView? = null
    private var imageCloseThree: ImageView? = null

    val cardListRet = MutableLiveData<JsonResult<UserCards>>()
    val isLoading = MutableLiveData<Boolean>(false)
    var payMoney = MutableLiveData<String>("")
    var payBankCardID = MutableLiveData<String>("")
    var tokenNo = MutableLiveData<String>("")
    val cardPay = MutableLiveData<JsonResult<Ret>>()

    lateinit var vm: MiddleVm

    override fun getV(): Int {
        return R.layout.dialog_pay_detail
    }

//    fun save_card(id: String, card_id: String) {
//        this.isLoading.value = true
//        vm.hold({
//            vm.server.save_card(id!!, card_id)
//        }, {
//            isLoading.value = true
//        }, success = {
//            cardPay.value = it
//        }, complete = {
//            isLoading.value = false
//        })
//    }

    fun holdCall() {
        if (isLoading.value!!)
            return
        vm.hold({
            vm.server.user_card_list()
        }, {
            isLoading.value = true
        }, success = {
            cardListRet.value = it
        }, complete = {
            isLoading.value = false
        })
    }

    val mAdapter: Bank3Adapter by lazy {
        Bank3Adapter(context).apply {
            itemClick = {
                LogUtils.i(it.bank_name + " - " + it.card_id)


                val slide_left_to_left = AnimationUtils.loadAnimation(context, R.anim.slide_left_to_left)
                val slide_right_to_left = AnimationUtils.loadAnimation(context, R.anim.slide_right_to_left)
                val slide_left_to_right = AnimationUtils.loadAnimation(context, R.anim.slide_left_to_right)
                val slide_left_to_left_in = AnimationUtils.loadAnimation(context, R.anim.slide_left_to_left_in)
                rePayDetail!!.startAnimation(slide_left_to_left_in)
                rePayDetail!!.visibility = View.VISIBLE
                LinPayWay!!.startAnimation(slide_left_to_right)
                LinPayWay!!.visibility = View.GONE


                var card4 = "(${it.card_id.substring(it.card_id.length - 4, it.card_id.length)})"
//                var cTypeStr = when (e.c_type) {
//                    0 -> "储蓄卡"
//                    1 -> "信用卡"
//                    else -> ""
//                }
                if (it.bank_name != null && it.bank_name!!.isNotBlank()) {
                    binding.payBank = it.bank_name + card4 + "\t" //+ cTypeStr
                } else {
                    binding.payBank = it.card_id + "\t" //+ cTypeStr
                }
                payBankCardID.value = it.card_id
                tokenNo.value = it.token_no

//                save_card(it.id, it.card_id)
//                cancel()
//                if (intent.getBooleanExtra("select", false)) {
//                    setResult(Activity.RESULT_OK, Intent().apply {
//                        putExtra("address", it)
//                    })
//                    finish()
//                }
            }
//            defItem = {
//                LogUtils.i(it.card_id)
////                viewModel.defAddr(it)
//            }
        }
    }

    var onSelectBank: ((money: String, bankNo: String, tokenNo: String) -> Unit)? = null

    override fun postBinding() {
        binding.event = this
//        StoreUtil.getBean<UserInfo>(context)?.let {
//            income.set("${it.income}")
//            integral.set("${it.integral}")
//        }
//        binding.payBank = payBank.value
        binding.payMoney = payMoney.value

        initView()
        holdCall()
        cardListRet.observe(context, {
            it?.apply {
                if (isSuccess) {
                    data?.let {
                        mAdapter.submitList(it.card_list)

                        if (it.card_list.isNullOrEmpty()) {
                            binding.payBank = "添加银行卡"
                        }
                        it.card_list?.let {
                            if (it.isNotEmpty()) {
                                var e = it[0]
                                if (e != null) {
                                    var card4 = "(${e.card_id.substring(e.card_id.length - 4, e.card_id.length)})"
                                    var cTypeStr = when (e.c_type) {
                                        0 -> "储蓄卡"
                                        1 -> "信用卡"
                                        else -> ""
                                    }
                                    if (e.bank_name != null && e.bank_name!!.isNotBlank()) {
                                        binding.payBank = e.bank_name + card4 + "\t" + cTypeStr
                                    } else {
                                        binding.payBank = e.card_id + "\t" + cTypeStr
                                    }
                                    payBankCardID.value = e.card_id
                                    tokenNo.value = e.token_no
                                }
                            }
                        }

//                        if (it.address_list != null && it.address_list.size > 0) {
//                            emptyLayout.visibility = View.GONE
//                        } else {
//                            emptyLayout.errorType = (EmptyLayout.NODATA)
//                        }
                    }
                } else {
//                    if (adapter.itemCount == 0){
//                        emptyLayout.errorType = (EmptyLayout.NETWORK_ERROR)
//                    }

                }
            }
        })

        cardPay.observe(context, Observer {
            it?.let {
                if (it.isSuccess) {
//                    toast("操作成功")
                    holdCall()
                }
            }
        })

    }


    private fun initView() {

        rePayWay = findViewById<View>(R.id.re_pay_way) as RelativeLayout
        rePayDetail = findViewById<View>(R.id.re_pay_detail) as RelativeLayout //付款详情
        LinPayWay = findViewById<View>(R.id.lin_pay_way) as LinearLayout //付款方式
        rv = findViewById<View>(R.id.rv_bank) as RecyclerView //付款方式（银行卡列表）
//        lv = findViewById<View>(R.id.lv_bank) as ListView //付款方式（银行卡列表）
        reBalance = findViewById<View>(R.id.re_balance) as RelativeLayout //付款方式（余额）
        btnPay = findViewById<View>(R.id.btn_confirm_pay) as Button
        gridPasswordView = findViewById<View>(R.id.pass_view) as EditText
        linPass = findViewById<View>(R.id.lin_pass) as LinearLayout
        llCloseOne = findViewById<View>(R.id.ll_close_one) as LinearLayout
        imageCloseTwo = findViewById<View>(R.id.close_two) as ImageView
        imageCloseThree = findViewById<View>(R.id.close_three) as ImageView
        rePayWay!!.setOnClickListener(listener)
        reBalance!!.setOnClickListener(listener)
        btnPay!!.setOnClickListener(listener)
        llCloseOne!!.setOnClickListener(listener)
        imageCloseTwo!!.setOnClickListener(listener)
        imageCloseThree!!.setOnClickListener(listener)

        binding.rvBank.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }

    }

    var listener = View.OnClickListener { view ->
        val slide_left_to_left = AnimationUtils.loadAnimation(context, R.anim.slide_left_to_left)
        val slide_right_to_left = AnimationUtils.loadAnimation(context, R.anim.slide_right_to_left)
        val slide_left_to_right = AnimationUtils.loadAnimation(context, R.anim.slide_left_to_right)
        val slide_left_to_left_in = AnimationUtils.loadAnimation(context, R.anim.slide_left_to_left_in)
        when (view.id) {
            R.id.re_pay_way -> {
                rePayDetail!!.startAnimation(slide_left_to_left)
                rePayDetail!!.visibility = View.GONE
                LinPayWay!!.startAnimation(slide_right_to_left)
                LinPayWay!!.visibility = View.VISIBLE
            }
            R.id.re_balance -> {
                rePayDetail!!.startAnimation(slide_left_to_left_in)
                rePayDetail!!.visibility = View.VISIBLE
                LinPayWay!!.startAnimation(slide_left_to_right)
                LinPayWay!!.visibility = View.GONE
            }
            R.id.btn_confirm_pay -> {
                if (payBankCardID.value.isNullOrEmpty()) {
                    toast("请添加银行卡")
                    return@OnClickListener
                }
                if (payMoney.value.isNullOrEmpty()) {
                    toast("请输入金额")
                    return@OnClickListener
                }
                onSelectBank?.invoke(payMoney.value!!, payBankCardID.value!!, tokenNo.value!!)
//                rePayDetail!!.startAnimation(slide_left_to_left)
//                rePayDetail!!.visibility = View.GONE
//                linPass!!.startAnimation(slide_right_to_left)
//                linPass!!.visibility = View.VISIBLE
            }

            R.id.ll_close_one -> cancel()
            R.id.close_two -> cancel()
            R.id.close_three -> cancel()
            else -> {
            }
        }
    }

    fun addBank() {
        context.startActivity(Intent(context, CreateBank3Activity::class.java))
        cancel()
    }

}